package com.example.demo4

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import com.example.demo4.model.PersonInfo
import java.io.ObjectInputStream
import java.io.ObjectOutputStream

class PersonInfoFragment : Fragment() {

    private lateinit var etName: EditText
    private lateinit var etStudentId: EditText
    private lateinit var etPhone: EditText
    private lateinit var etEmail: EditText
    private lateinit var rgGender: RadioGroup
    private lateinit var rbMale: RadioButton
    private lateinit var rbFemale: RadioButton
    private lateinit var cbTravel: CheckBox
    private lateinit var cbReading: CheckBox
    private lateinit var cbGaming: CheckBox
    private lateinit var cbShopping: CheckBox
    private lateinit var btnSave: Button

    private var personInfo: PersonInfo = PersonInfo()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_person_info, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews(view)
        loadData()
        setupListeners()
    }

    private fun initViews(view: View) {
        etName = view.findViewById(R.id.etName)
        etStudentId = view.findViewById(R.id.etStudentId)
        etPhone = view.findViewById(R.id.etPhone)
        etEmail = view.findViewById(R.id.etEmail)
        rgGender = view.findViewById(R.id.rgGender)
        rbMale = view.findViewById(R.id.rbMale)
        rbFemale = view.findViewById(R.id.rbFemale)
        cbTravel = view.findViewById(R.id.cbTravel)
        cbReading = view.findViewById(R.id.cbReading)
        cbGaming = view.findViewById(R.id.cbGaming)
        cbShopping = view.findViewById(R.id.cbShopping)
        btnSave = view.findViewById(R.id.btnSave)
    }

    private fun setupListeners() {
        btnSave.setOnClickListener {
            saveData()
            Toast.makeText(requireContext(), "信息已保存", Toast.LENGTH_SHORT).show()
        }
    }

    private fun loadData() {
        try {
            val input = requireActivity().openFileInput("person_info")
            val objectInputStream = ObjectInputStream(input)
            personInfo = objectInputStream.readObject() as PersonInfo
            objectInputStream.close()
            input.close()

            // 更新UI
            etName.setText(personInfo.name)
            etStudentId.setText(personInfo.studentId)
            etPhone.setText(personInfo.phone)
            etEmail.setText(personInfo.email)

            // 设置性别
            when (personInfo.gender) {
                getString(R.string.radio_male) -> rbMale.isChecked = true
                getString(R.string.radio_female) -> rbFemale.isChecked = true
            }

            // 设置爱好
            if (personInfo.hobbies.isNotEmpty()) {
                cbTravel.isChecked = personInfo.hobbies.contains(getString(R.string.hobby_travel))
                cbReading.isChecked = personInfo.hobbies.contains(getString(R.string.hobby_reading))
                cbGaming.isChecked = personInfo.hobbies.contains(getString(R.string.hobby_gaming))
                cbShopping.isChecked = personInfo.hobbies.contains(getString(R.string.hobby_shopping))
            }
        } catch (e: Exception) {
            e.printStackTrace()
            // 文件不存在或读取失败，使用默认值
        }
    }

    private fun saveData() {
        personInfo.name = etName.text.toString()
        personInfo.studentId = etStudentId.text.toString()
        personInfo.phone = etPhone.text.toString()
        personInfo.email = etEmail.text.toString()

        personInfo.gender = if (rbMale.isChecked) {
            getString(R.string.radio_male)
        } else {
            getString(R.string.radio_female)
        }

        val selectedHobbies = mutableListOf<String>()
        if (cbTravel.isChecked) selectedHobbies.add(getString(R.string.hobby_travel))
        if (cbReading.isChecked) selectedHobbies.add(getString(R.string.hobby_reading))
        if (cbGaming.isChecked) selectedHobbies.add(getString(R.string.hobby_gaming))
        if (cbShopping.isChecked) selectedHobbies.add(getString(R.string.hobby_shopping))
        personInfo.hobbies = selectedHobbies.joinToString(separator = ", ")

        try {
            val output = requireActivity().openFileOutput("person_info", android.content.Context.MODE_PRIVATE)
            val objectOutputStream = ObjectOutputStream(output)
            objectOutputStream.writeObject(personInfo)
            objectOutputStream.close()
            output.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onStop() {
        super.onStop()
        saveData()
    }

    companion object {
        @JvmStatic
        fun newInstance(): PersonInfoFragment {
            return PersonInfoFragment()
        }
    }
}
